package com.qf.mpswaggershiro.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mpswaggershiro.ex.MyexClass;
import com.qf.mpswaggershiro.user.entity.Users;
import com.qf.mpswaggershiro.user.dao.UsersDao;
import com.qf.mpswaggershiro.user.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.mpswaggershiro.utils.Constants;
import com.qf.mpswaggershiro.utils.SaltUtils;
import com.qf.mpswaggershiro.vo.RegistVo;
import com.qf.mpswaggershiro.vo.Vo;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 用户  服务实现类   注册
 * </p>
 *
 * @author cui
 * @since 2023-02-13
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersDao, Users> implements IUsersService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void regist(RegistVo registVo) throws Exception {
        //2.接收json数据并且解决跨域问题
        String username = registVo.getUsername();
        String password = registVo.getPassword();
        String repassword = registVo.getRepassword();
        if (!password.equals(repassword)) {
            throw new Exception("密码不一致");
        }

                //3.检查用户名是否重复
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username",username);

        Users users = getOne(usersQueryWrapper);
        if (users!=null){
            throw new Exception("用户名已存在");
        }
       //密码加密  加盐
        Users user = new Users();

        //4.插入数据（new一个user并且set属性）
        String salt = SaltUtils.getSalt(Constants.SALT_LENTH);
        //设置salt到user对象
        user.setSalt(salt);
        //生成加密的密码
        //String password = registVo.getPassword();
        //创建shiro提供的 加密对象
        //第一个参数 密码原文  第二个是 随机盐  第三个是hash次数
        Md5Hash md5Hash = new Md5Hash(password, salt, Constants.HASH_TIMES);

        String sercetPwd = md5Hash.toHex();

        user.setPassword(sercetPwd);

        user.setUsername(username);

        user.setUserRegtime(new Date());

        user.setUserModtime(new Date());

         save(user);



    }
}
